package com.drinks.yiniang.ui.activity.camera;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.base.BaseQuickRCVAdapter;
import com.drinks.yiniang.adapter.photo.AlbumPhotosAdapter;
import com.drinks.yiniang.adapter.photo.DraftsPhotos2Adapter;
import com.drinks.yiniang.adapter.photo.DraftsPhotosAdapter;
import com.drinks.yiniang.common.camera.album.AlbumModel;
import com.drinks.yiniang.common.camera.album.Result;
import com.drinks.yiniang.common.camera.album.Setting;
import com.drinks.yiniang.common.recycler.decoration.AchievementItemDecoration;
import com.drinks.yiniang.common.recycler.decoration.AlbumPhotosItemDecoration;
import com.drinks.yiniang.common.recycler.decoration.DraftsPhotosItemDecoration;
import com.drinks.yiniang.common.recycler.decoration.ItemSpacesDecoration;
import com.drinks.yiniang.entity.photo.Photos;
import com.drinks.yiniang.ui.activity.community.CommunityPublishActivity;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.utils.FileUtils;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.RecyclerUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.FileProviderUtils;
import com.hansen.library.utils.PermissionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 相册
 *
 * @author han
 * @date 2019/09/16
 */
public class AlbumActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        BaseQuickAdapter.OnItemClickListener, AlbumPhotosAdapter.OnAlbumPhotoChangeListener {

    private final int REQ_DRAFTS_MANAGE_CODE = 0x01;
    private final int REQ_NEXT_STEP_CODE = 0x02;

    //nav
    private NavigationBarLayout nav_bar_album;
    //列表
    private BaseRecyclerView rcv_album_all;
    //草稿列表
    private BaseRecyclerView rcv_album_drafts;
    //header view
    private ImageView iv_album_photos_first;
    //草稿标题
    private TextView tv_album_photos_drafts_title;
    //管理草稿
    private TextView tv_album_photos_drafts_manager;

    private AlbumPhotosAdapter mAlbumPhotosAdapter;
    private DraftsPhotos2Adapter mDraftsPhotosAdapter;

    private AlbumModel mAlbumModel;

    //是否从草稿选取
    private boolean isChooseByDrafts;

    @Override
    protected void initView() {
        nav_bar_album = findViewById(R.id.nav_bar_album);

        rcv_album_all = findViewById(R.id.rcv_album_all);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        initAdapter();
        initDraftsAdapter();

        if (PermissionUtils.checkAndRequestPermissionsInActivity(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})) {
            hasPermissions();
        } else {//没有权限
            //permissionView.setVisibility(View.VISIBLE);
        }
    }

    private void initAdapter() {
        rcv_album_all.setLayoutManager(RecyclerUtils.getVerticalGridLayout(mContext, 3));
        rcv_album_all.addItemDecoration(AlbumPhotosItemDecoration.getItemPXDecoration(2));

        mAlbumPhotosAdapter = new AlbumPhotosAdapter(mContext, new ArrayList<Photos>());
        mAlbumPhotosAdapter.addHeaderView(getHeaderView());
        //mAlbumPhotosAdapter.setHeaderAndEmpty(true);
        //mAlbumPhotosAdapter.setCommonEmpty(getLayoutInflater(), rcv_album_all);
        mAlbumPhotosAdapter.bindToRecyclerView(rcv_album_all);
    }

    private void initDraftsAdapter() {
        rcv_album_drafts.setLayoutManager(RecyclerUtils.getHorizontalLinearLayout(mContext));
        rcv_album_drafts.addItemDecoration(DraftsPhotosItemDecoration.getItemDPDecoration(12));

        mDraftsPhotosAdapter = new DraftsPhotos2Adapter(mContext, new ArrayList<Photos>());
        mDraftsPhotosAdapter.bindToRecyclerView(rcv_album_drafts);
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_album_photos, (ViewGroup) rcv_album_all.getParent(), false);

        rcv_album_drafts = mHeaderView.findViewById(R.id.rcv_album_drafts);

        iv_album_photos_first = mHeaderView.findViewById(R.id.iv_album_photos_first);

        tv_album_photos_drafts_title = mHeaderView.findViewById(R.id.tv_album_photos_drafts_title);
        tv_album_photos_drafts_manager = mHeaderView.findViewById(R.id.tv_album_photos_drafts_manager);

        tv_album_photos_drafts_manager.setOnClickListener(this);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_album.setOnNavgationBarClickListener(this);
        mAlbumPhotosAdapter.setOnAlbumPhotoChangeListener(this);
        mDraftsPhotosAdapter.setOnAlbumPhotoChangeListener(this);
    }

    @Override
    public void widgetClick(View v) {
        if(v.getId() == R.id.tv_album_photos_drafts_manager) {
            startActivityForResult(new Intent(mContext, DraftsManageActivity.class), REQ_DRAFTS_MANAGE_CODE);
        }
    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_album;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        //next step
        if(CommonUtils.isEmptyList(Result.mPhotos)) {
            ToastUtils.showShort("请选择图片");
            return;
        }

        startActivityForResult(new Intent(mContext, PreviewPhotosActivity.class), REQ_NEXT_STEP_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Constants.RESULT_CODE_NORMAL) {
            switch (requestCode) {
                case REQ_DRAFTS_MANAGE_CODE://草稿编辑返回
                    getDraftList();
                    break;
                case REQ_NEXT_STEP_CODE://下一步返回
                    setResult(Constants.RESULT_CODE_NORMAL);
                    finish();
                    break;
                    default:
                        break;
            }
        }
    }

    private void hasPermissions() {
        showLoadingDialog();

        Setting.fileProviderAuthority = FileProviderUtils.getFileProviderName(mContext);

        getDraftList();

        AlbumModel.CallBack albumModelCallBack = new AlbumModel.CallBack() {
            @Override
            public void onAlbumWorkedCallBack() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //onAlbumWorkedDo();
                        dismissDialog();

                        if (mAlbumModel.getAlbumItems().isEmpty()) {
                            ToastUtils.showShort(R.string.text_no_album_photos);
                            finish();
                            return;
                        }

                        if(mAlbumPhotosAdapter == null) {
                            return;
                        }

                        mAlbumPhotosAdapter.getData().clear();
                        mAlbumPhotosAdapter.addData(mAlbumModel.getCurrAlbumItemPhotos(0));
                    }
                });
            }
        };
        mAlbumModel = AlbumModel.getInstance();
        //showProgress(true);
        mAlbumModel.query(this, albumModelCallBack);
    }

    //获取草稿
    private void getDraftList() {
        List<String> draftFiles = FileUtils.getAllDraftFiles(Constants.RootDrafts);
        List<Photos> draftsList = new ArrayList<>();

        for(String path: draftFiles) {
            Photos photos = new Photos();

            photos.path = path;

            draftsList.add(photos);
        }

        if(draftsList.size() <= 0) {
            iv_album_photos_first.setVisibility(View.GONE);
            tv_album_photos_drafts_title.setVisibility(View.GONE);
            tv_album_photos_drafts_manager.setVisibility(View.GONE);
            rcv_album_drafts.setVisibility(View.GONE);
        } else {
            if(iv_album_photos_first.getVisibility() == View.GONE) {
                iv_album_photos_first.setVisibility(View.VISIBLE);
                tv_album_photos_drafts_title.setVisibility(View.VISIBLE);
                tv_album_photos_drafts_manager.setVisibility(View.VISIBLE);
                rcv_album_drafts.setVisibility(View.VISIBLE);
            }

            GlideUtils.loadLocalImage(mContext, iv_album_photos_first, draftsList.get(0).path);
        }

        mDraftsPhotosAdapter.getData().clear();
        mDraftsPhotosAdapter.addData(draftsList);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onPhotosChange(BaseQuickRCVAdapter adapter) {
        mDraftsPhotosAdapter.notifyDataSetChanged();
        mAlbumPhotosAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        Setting.clear();
        Result.clear();
        if (mAlbumModel != null) {
            mAlbumModel.stopQuery();
        }
        super.onDestroy();
    }
}
